package com.retail.order.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.retail.core.common.AbstractCommonController;
import com.retail.core.entity.ParamReq;

import com.retail.core.entity.result.PageResult;
import com.retail.core.entity.result.Result;
import com.retail.global.security.LoginUser;
import com.retail.global.security.LoginUserUtil;
import com.retail.global.annon.TraceLog;
import com.retail.order.entity.request.SysAdminVerifyRequest;
import com.retail.order.entity.vo.SysAdminVerifyVo;
import com.retail.order.service.SysAdminVerifyService;
import com.retail.wxchat.entity.vo.WxchatMiniappConfigVo;
import com.retail.wxchat.service.WxchatMiniappConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.retail.core.util.CommonConstants.BUSSINESS_ROLE;

/**
 * 用户核销单子 API
 *
 * @author Administrator
 */
@Api(tags = "用户核销单子 API")
@RestController
@RequestMapping("/sysAdminVerify")
public class SysAdminVerifyController extends AbstractCommonController<SysAdminVerifyService, SysAdminVerifyRequest, SysAdminVerifyVo> {

    @Autowired
    private SysAdminVerifyService sysAdminVerifyService;

    @Autowired
    private WxchatMiniappConfigService wxchatMiniappConfigService;

    private final static String SCENE_TRANSFER_FILE = "scene_transfer_default_template.xls";


    @TraceLog()
    @GetMapping("{id}")
    public Result getModel(@PathVariable("id") Long id) {
        return super.getModel(sysAdminVerifyService, id);
    }

    @TraceLog()
    @PostMapping
    @ApiOperation("保存用户核销单子")
    public Result<Integer> save(@RequestBody SysAdminVerifyRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());
        return super.save(sysAdminVerifyService, request);
    }

    @TraceLog()
    @PostMapping("operUserMonthVerify")
    @ApiOperation("核销信息")
    public Result<Integer> operUserMonthVerify(@RequestBody SysAdminVerifyRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());
        new Thread(() -> sysAdminVerifyService.operUserMonthVerify(request)).start();

        return Result.success("核销成功");
    }

    @TraceLog()
    @PostMapping("operUserYearVerify")
    @ApiOperation("核销年份信息")
    public Result<Integer> operUserYearVerify(@RequestBody SysAdminVerifyRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());
        Integer count = sysAdminVerifyService.operUserYearVerify(request);

        return Result.success(count);
    }

    @TraceLog()
    @PutMapping
    @ApiOperation("更新用户核销单子")
    public Result<Integer> update(@RequestBody SysAdminVerifyRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());
        return super.update(sysAdminVerifyService, request);
    }

    @TraceLog()
    @PostMapping("verifyOrders")
    @ApiOperation("核销单子")
    public Result<Integer> verifyOrder(@RequestBody SysAdminVerifyRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());
        return sysAdminVerifyService.verifyOrder(request);
    }

    @TraceLog()
    @PostMapping("tixianOrders")
    @ApiOperation("提现单子")
    public Result<Integer> tixianOrders(@RequestBody SysAdminVerifyRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());
        return sysAdminVerifyService.tixianOrders(request);
    }

    @TraceLog()
    @PostMapping("listPage")
    @ApiOperation("用户核销单子-查询")
    public Result<List<SysAdminVerifyVo>> listPage(@RequestBody ParamReq<SysAdminVerifyRequest> req) {
        return super.listPage(sysAdminVerifyService, req);
    }

    @TraceLog()
    @PostMapping("countPage")
    @ApiOperation("用户核销单子-统计")
    public Result<Integer> countPage(@RequestBody ParamReq<SysAdminVerifyRequest> req) {
        return super.countPage(sysAdminVerifyService, req);
    }

    @TraceLog()
    @PostMapping("page")
    @ApiOperation("用户核销单子-分页数据")
    public Result<PageResult> page(@RequestBody ParamReq<SysAdminVerifyRequest> req) {
        SysAdminVerifyRequest adminRequest = req.getEntity();
        Long adminId = getLoginUserId();
        LoginUser loginUser = LoginUserUtil.getPrincipal();
        Set<Long> roles = loginUser.getRolePos().stream().map(f -> f.getId()).collect(Collectors.toSet());
        Set<Long> searchIds = new HashSet<Long>();
        if (roles.size() == 1 && ObjectUtil.contains(roles, BUSSINESS_ROLE)) {
            adminRequest.setSearchOwnerMsg(1);
            searchIds.add(adminId);
            adminRequest.setSearchUserIds(searchIds);
        }
        req.setEntity(adminRequest);

        return super.page(sysAdminVerifyService, req);
    }

    /**
     * 导出数据
     *
     * @param req
     * @return
     */
    @TraceLog()
    @PostMapping("pageExports")
    @ApiOperation("核销-导出")
    public void pageExports(@RequestBody ParamReq<SysAdminVerifyRequest> req, HttpServletResponse httpServletResponse) throws UnsupportedEncodingException {
        try {
            SysAdminVerifyRequest request = req.getEntity();
            if (ObjectUtil.equal(request.getVerifyType(), 1)) {
                createVerifyXls(request.getIds(), request.getVerifyMonth(), request.getVerifyType(), httpServletResponse);
            } else if (ObjectUtil.equal(request.getVerifyType(), 2)) {
                createVerifyXls(request.getIds(), request.getVerifyYear(), request.getVerifyType(), httpServletResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @TraceLog()
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除用户核销单子")
    public Result<Integer> delete(@PathVariable("id") Long id) {
        return super.delete(sysAdminVerifyService, id);
    }

    @TraceLog()
    @ApiOperation("批量删除用户核销单子")
    @DeleteMapping("{ids}")
    public Result<Integer> batchDelete(List<Long> ids) {
        return super.batchDelete(sysAdminVerifyService, ids);
    }

    @Override
    public Long getLoginUserId() {
        return LoginUserUtil.getUserId();
    }

    /**
     * 生成核销文件
     *
     * @param verifyDate 核销时间
     * @param verifyType 类型 1-月度 2-年度
     * @throws FileNotFoundException
     */
    public void createVerifyXls(List<Long> ids, String verifyDate, Integer verifyType, HttpServletResponse httpServletResponse) throws IOException {
        if (!((verifyType == 1 && verifyDate.matches("\\d{4}-\\d{2}")) || verifyType == 2 && verifyDate.matches("\\d{4}"))) {
            return;
        }

        String pcid = verifyType == 1 ? ("vpcm" + verifyDate.replace("-", "")) : verifyType == 2 ? ("vpcy" + verifyDate) : "";

        InputStream oraInputStream = getClass().getClassLoader().getResourceAsStream(SCENE_TRANSFER_FILE);
        File output = File.createTempFile(File.separator + System.currentTimeMillis(), ".xls") ;

        IoUtil.copy(oraInputStream, new FileOutputStream(output));

        WxchatMiniappConfigVo configVo = wxchatMiniappConfigService.getModelLimit1();

        ExcelWriter writer = ExcelUtil.getWriter(output);
        // 商家批次单号（必填）
        writer.writeCellValue(1, 1, pcid);
        // 批次名称（必填）
        writer.writeCellValue(1, 2, verifyType == 1 ? ("vpcm" + verifyDate + "月度核销订单") : verifyType == 2 ? ("vpcy" + verifyDate + "年度核销订单") : "");
        // 转账appid（必填）
        writer.writeCellValue(1, 3, configVo.getAppId());

        // 得到核销信息
        List<SysAdminVerifyVo> verifyAdmins = adminVerifyList(verifyDate, verifyType);
        List<SysAdminVerifyVo> res = new ArrayList<>();
        for (SysAdminVerifyVo va : verifyAdmins) {
            if (ObjectUtil.isEmpty(ids) || ids.size() == 0) {
                res.add(va);
            } else {
                if (ObjectUtil.contains(ids, va.getId())) {
                    res.add(va);
                }
            }
        }

        BigDecimal total = new BigDecimal(0);

        int rows = 10;
        for (int i = 0; i < res.size(); i++) {
            SysAdminVerifyVo verify = res.get(i);
            Long verifyId = verify.getId();
            writer.writeCellValue(0, rows + i, pcid + "VERID" + verifyId);
            writer.writeCellValue(1, rows + i, verify.getOpenid());
            writer.writeCellValue(2, rows + i, verify.getAdminName());
            writer.writeCellValue(3, rows + i, "");
            writer.writeCellValue(4, rows + i, verify.getVerifyPrice());
            writer.writeCellValue(5, rows + i, verifyDate + "核销金额");
            total = total.add(ObjectUtil.defaultIfNull(verify.getVerifyPrice(), new BigDecimal(0)));
        }
        writer.writeCellValue(1, 4, total.doubleValue() + "");
        writer.writeCellValue(1, 5, res.size());
        writer.writeCellValue(1, 6, verifyDate + "核销金额");
        writer.writeCellValue(1, 7, 1001);

        httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
        String excelName = pcid + "_核销名单";
        excelName = URLEncoder.encode(excelName, "utf-8");
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + excelName + ".xls");

        ServletOutputStream excelOut = null;
        try {
            excelOut = httpServletResponse.getOutputStream();
            writer.flush(excelOut, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
        IoUtil.close(excelOut);
    }


    public List<SysAdminVerifyVo> adminVerifyList(String verifyDate, Integer verifyType) {
        Integer examineVerify = 1;
        Integer tixianFlag = 0;
        List<SysAdminVerifyVo> list = sysAdminVerifyService.findVerifyList(verifyType, verifyDate, examineVerify, tixianFlag);
        System.out.println(list);
        return list;
    }
}
